using System;
using System.Web;
using System.Collections.Generic;
using Common;
using Common.Events;
using Common.Search;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using SearchModule.Events;
using SearchModule.Models;

namespace SearchModule.Services
{
    /// <summary>
    /// Dummy data service class. Provides a dummy data model.
    /// Replace with your real data model and/or data service proxy.
    /// </summary>
    public class DataService : IDataService
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;
        public DataService(IEventAggregator eventAggregator, IRegionManager regionManager)
        {
            _eventAggregator = eventAggregator;
            _regionManager = regionManager;
            // subscribe to the SearchRequestEvent
            _eventAggregator.GetEvent<SearchRequestEvent>().Subscribe(HandleSearchRequest);

            // subscribe to the SearchResponseEvent
            _eventAggregator.GetEvent<SearchResponseEvent>().Subscribe(HandleSearchResponse);
        }

        private SearchResults model;
        private void HandleSearchResponse(SearchResponseEventData data)
        {
            if (model == null)
                model = new SearchResults();

            model.Add(data.SearchResult);

            // if this is the first result, we should activate the view
            if (model.Count == 1)
                this._regionManager.RequestNavigate(RegionNames.MainRegion,
                                                    new Uri("SearchResultsView", UriKind.Relative));

            // notify results view
            _eventAggregator.GetEvent<SearchResultsUpdatedEvent>().Publish(null);
        }

        private void HandleSearchRequest(SearchRequestEventData data)
        {
            if (!string.IsNullOrEmpty(data.SearchRequest.RawRequest))
            {
                var query = HttpUtility.UrlEncode(data.SearchRequest.RawRequest);

                var gParameters = new UriQuery();
                gParameters.Add("uri", string.Format("https://www.google.com/#hl=en&q={0}", query));
                var gURI = new Uri("GenericWebView" + gParameters.ToString(), UriKind.Relative);

                var bParameters = new UriQuery();
                bParameters.Add("uri", string.Format("http://www.bing.com/search?q={0}", query));
                var bURI = new Uri("GenericWebView" + bParameters.ToString(), UriKind.Relative);

                var result = new SearchResult();
                result.ResultHeader = "Web Results";
                result.Results = new List<SearchResultItem>()
                                     {
                                         new SearchResultItem()
                                             {
                                                 ItemText = string.Format("Search '{0}' on Google", data.SearchRequest.RawRequest),
                                                 ItemUri = gURI,
                                                 TargetRegion = RegionNames.MainRegion
                                             },
                                         new SearchResultItem()
                                             {
                                                 ItemText = string.Format("Search '{0}' on Bing", data.SearchRequest.RawRequest),
                                                 ItemUri = bURI,
                                                 TargetRegion = RegionNames.MainRegion
                                             }
                                     };
                _eventAggregator.GetEvent<SearchResponseEvent>().Publish(new SearchResponseEventData(){SearchResult = result}); 
            }
        }

        public void MakeSearchRequest(string parameter)
        {
            // clear the data on each new search request
            ClearModel();
            var req = new SearchRequest() { RawRequest = parameter };
            _eventAggregator.GetEvent<SearchRequestEvent>().Publish(new SearchRequestEventData() { SearchRequest = req });
        }

        public void ClearModel()
        {
            if(model != null)
                model.Clear();
        }

        public SearchResults GetModel()
        {
            if (model == null)
            {
                model = new SearchResults();

                // Dummy Data.
                //model.Add(new DataItem() { Id = "1", Name = "Item 1", Description = "Description 1" });
                //model.Add(new DataItem() { Id = "2", Name = "Item 2", Description = "Description 2" });
                //model.Add(new DataItem() { Id = "3", Name = "Item 3", Description = "Description 3" });
                //model.Add(new DataItem() { Id = "4", Name = "Item 4", Description = "Description 4" });
            }

            return model;
        }
    }
}
